import 'package:flutter/cupertino.dart';
import 'package:visibility_detector/visibility_detector.dart';

///监听可见性
class FFVisibility extends StatefulWidget {
  Widget child;
  Function()? onAppear;
  Function()? onDisappear;

  FFVisibility({
    Key? key,
    required this.child,
    this.onAppear,
    this.onDisappear,
  }) : super(key: key);

  @override
  State<FFVisibility> createState() => _FFVisibilityState();
}

class _FFVisibilityState extends State<FFVisibility> {

  GlobalKey key = GlobalKey();
  bool? isVisible;

  @override
  Widget build(BuildContext context) {
    return VisibilityDetector(
      key: key,
      onVisibilityChanged: (visibilityInfo) {

        if (!mounted) {
          return;
        }

        bool isTmpVisible = visibilityInfo.visibleFraction > 0.0;
        if (isVisible == null && !isTmpVisible) {
          isVisible = isTmpVisible;
          return;
        }
        if (isVisible != isTmpVisible) {
          isVisible = isTmpVisible;

          if (isVisible!) {
            if (widget.onAppear != null) {
              widget.onAppear!();
            }
          } else {
            if (widget.onDisappear != null) {
              widget.onDisappear!();
            }
          }
        }


      },
      child: widget.child,
    );
  }
}
